//通过外部类实现事件监听

import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Vector;

import javax.swing.JOptionPane;
import javax.swing.JRadioButton;

public class addListener implements ActionListener{
	UI ui;//定义界面类
	//定义构造方法
	public addListener(UI ui) {
		this.ui = ui;
	}
	@Override
	public void actionPerformed(ActionEvent e) {
		//获取内容，同时进行相关操作
		String name = this.ui.name_t.getText();
		String sex = null;
		for (Component c : this.ui.panel1.getComponents()) {
			if(c instanceof JRadioButton) {
				sex = ((JRadioButton) c).getText();
			}
		}
		String phone = this.ui.phone_t.getText();
		String grade = this.ui.grade_t.getText();
		
		try {
			Class.forName(this.ui.JDBC_DRIVER);
			this.ui.conn = DriverManager.getConnection(this.ui.URL, this.ui.USER, this.ui.PASSWORD);
			//判断数据库中是否有相关数据
			this.ui.sql = "SELECT * FROM Grades where name = ?";
			this.ui.pstmt = this.ui.conn.prepareStatement(this.ui.sql);
			this.ui.pstmt.setString(1, name);
			this.ui.rs = this.ui.pstmt.executeQuery();
			if(!this.ui.rs.next()) { //如果没有找到县官数据，进行数据添加
				String sql = "INSERT INTO Grades (Name, Sex, Phone, Grade) VALUES (?, ?, ?, ?)";
				this.ui.pstmt = this.ui.conn.prepareStatement(sql);
				this.ui.pstmt.setString(1, name);
				this.ui.pstmt.setString(2, sex);
				this.ui.pstmt.setString(3, phone);
				this.ui.pstmt.setString(4, grade);
				this.ui.pstmt.executeUpdate();
				//更新前端数据表中内容
				Vector vrow = new Vector();
				vrow.add(name);
				vrow.add(sex);
				vrow.add(phone);
				vrow.add(grade);
				this.ui.vdata.add(vrow);
				this.ui.Table.updateUI();
				JOptionPane.showMessageDialog(null, "添加成功");
			}else {
				//弹窗提示已经存在当前的数据
				JOptionPane.showMessageDialog(null, "已经存在这个数据！");
				this.ui.name_t.setText("");
				this.ui.phone_t.setText("");
				this.ui.grade_t.setText("");
			}
			} catch (ClassNotFoundException | SQLException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}finally {
			try {
				//结束释放所有资源
				this.ui.rs.close();
				this.ui.pstmt.close();
				this.ui.conn.close();
			} catch (SQLException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
		}
		
	}
}
